package com.zp.oj.judge;

import cn.hutool.json.JSONUtil;
import com.zp.oj.common.ErrorCode;
import com.zp.oj.exception.BusinessException;
import com.zp.oj.judge.CodeSandBox.CodeSandBox;
import com.zp.oj.judge.CodeSandBox.CodeSandBoxFactory;
import com.zp.oj.judge.CodeSandBox.CodeSandBoxProxy;
import com.zp.oj.judge.model.ExecuteCodeRequest;
import com.zp.oj.judge.model.ExecuteCodeSandResponse;
import com.zp.oj.judge.strategy.JudgeContent;
import com.zp.oj.judge.strategy.JudgeManage;
import com.zp.oj.judge.strategy.JudgeStrategy;
import com.zp.oj.model.dto.question.JudgeCase;
import com.zp.oj.judge.model.JudgeInfo;
import com.zp.oj.model.entity.Question;
import com.zp.oj.model.entity.QuestionSubmit;
import com.zp.oj.model.enums.JudgeInfoEnum;
import com.zp.oj.model.enums.QuestionSubmitStatusEnum;
import com.zp.oj.model.vo.QuestionSubmitVO;
import com.zp.oj.service.QuestionService;
import com.zp.oj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Value("${codesandbox.type:example}")
    private String type;
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionSubmitService questionSubmitService;


    public void checkMessage(QuestionSubmit questionSubmit, Question question){
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交题目不存在");
        }
        // 如果不为等待状态
        if(questionSubmit.getStatus() != QuestionSubmitStatusEnum.WAITING.getValue()){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题中");
        }
    }

    /**
     * 修改题目提交状态
     * @param questionSubmitId
     */
    public QuestionSubmit changeQuestionSubmitMessage(Long questionSubmitId){
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        questionSubmitUpdate.setId(questionSubmitId);
        Boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交状态更新错误");
        }
        System.out.println("doJudge execute");
        return questionSubmitUpdate;
    }


    @Override
    public QuestionSubmitVO doJudge(Long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);

        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        // 检查题目状态
        checkMessage(questionSubmit, question);

        // 修改提交状态信息
        QuestionSubmit questionSubmitUpdate = changeQuestionSubmitMessage(questionSubmitId);

        // 调用代码沙箱
        CodeSandBox codeSandBox = CodeSandBoxFactory.newInstance(type);
        codeSandBox = new CodeSandBoxProxy(codeSandBox);

        // 获取提交信息
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        // 获取提交题目信息
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputs = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .inputs(inputs)
                .language(language)
                .build();
        //获取返回信息
        ExecuteCodeSandResponse executeCodeSandResponse = codeSandBox.executeCode(executeCodeRequest);

        //根据返回信息进行检查
        JudgeContent judgeContent = new JudgeContent();
        judgeContent.setInputs(inputs);
        judgeContent.setOutPuts(executeCodeSandResponse.getOutputs());
        judgeContent.setQuestion(question);
        // to do
        judgeContent.setJudgeInfo(executeCodeSandResponse.getJudgeInfo());
        judgeContent.setJudgeCaseList(judgeCaseList);
        judgeContent.setQuestionSubmit(questionSubmit);


        JudgeStrategy judgeManage = new JudgeManage();
        JudgeInfo judgeInfo = judgeManage.doJudge(judgeContent, executeCodeSandResponse);
        System.out.println("更新完之后" + judgeInfo);

        // 修改判题信息
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));

        Boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交状态更新错误");
        }

        // 修改题目信息
        question.setSubmitNum(question.getSubmitNum() + 1);
        if(judgeInfo.getMessage().equals("Accept")){
            question.setAcceptNum(question.getAcceptNum() + 1);
        }
        update = questionService.updateById(question);
        if(!update){
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR, "题目信息更新错误");
        }

        // 再次获取状态返回前端
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmitResult);
        questionSubmitVO.setExtraMessage(executeCodeSandResponse.getMessage());
        return questionSubmitVO;

    }
}
